package tcp;

import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * As it turns out, this class is almost completely 
 * unnecessary.  It encapsulates a ThreadedSessionHandler
 * entirely for convenience. It delegates the 
 * responsibility of TCPSubject to the ThreadedSessionHandler
 * in a near decorator pattern fashion. True decorator 
 * (with interfaces) was no implemented because this is
 * built on old code from February.
 * 
 * Note: The a new thread of execution  is started for you here,
 * unlike in the TCPServer class. 
 * 
 * @author Kristopher L. Kalish, James Madison University
 * @version 1 - February 23, 2008
 * @version 2 - April 6, 2008 
 * (Rewritten to use the more versatile SessionHandler/Observer combo)
 * (Probably still needs more restructuring)
 *
 */
public class TCPClient implements TCPSubject
{
	private int            port;
	private Socket         clientSocket;
	private ThreadedSessionHandler handler;
	private String         host;

	public TCPClient(String host, int port)
	{
		this.host = host;
		this.port = port;
		
		System.out.println("Attempting to connect to " + host + ":" + port + ".");
		try {
			clientSocket = new Socket(host, port);
			System.out.println("Socket created.");
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
		
		handler = new ThreadedSessionHandler(clientSocket, false);		
		handler.start();
	}
	
	public void addObserver(TCPObserver observer)
	{
		handler.addObserver(observer);
	}
	
	public void notifyObservers(Object o)
	{
		handler.notifyObservers(o);
	}
	
	public void removeObserver(TCPObserver observer)
	{
		handler.removeObserver(observer);
	}
	
	public void send(Object o)
	{
		handler.send(o);
	}
}